<?php

namespace app\common\middleware;

use core\Middleware;
use core\Request;
use core\Response;
use core\AppException;

class CsrfMiddleware implements Middleware {
    public function handle($request, $next) {
        // 只验证非GET请求
        if (Request::getMethod() !== 'GET') {
            $token = Request::getParam('_csrf_token');
            $sessionToken = $_SESSION['csrf_token'] ?? null;
            
            if (!$token || $token !== $sessionToken) {
                throw new AppException('CSRF验证失败', 403);
            }
        }
        
        // 生成CSRF令牌
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        
        // 将CSRF令牌添加到响应头
        Response::setHeader('X-CSRF-Token', $_SESSION['csrf_token']);
        
        return $next($request);
    }
}